// import { Loading } from 'element-ui';
import {checkUrl} from '@/utils/utils'
import axios from 'axios';


axios.defaults.timeout = 30000;
//返回其他状态吗
axios.defaults.validateStatus = function (status) {
    return status >= 200 && status <= 500; // 默认的
};
//跨域请求，允许保存cookie
// let loadingInstance = '';
// axios.defaults.withCredentials = true;
axios.interceptors.request.use(config => {
    console.log(2)
    // loadingInstance = Loading.service({
    //   text: '拼命加载中',
    //   background: 'rgba(0,0,0,0)',
    //   spinner: 'el-icon-loading'
    // });
    if (!checkUrl(config.url)) config.url = window.$glob.url + config.url;
    let header = window.$glob.header || {};
    config.headers = Object.assign(config.headers, header);
    //获取全局参数
    if (typeof (config.data) === 'object') {
        let data = window.$glob.query || {}
        let key;
        if (config.method == 'get') {
            key = "params"
        } else if (config.method == 'post') {
            key = "data"
        }
        if (typeof (config[key]) === 'object') {
            config[key] = Object.assign(config[key] || {}, data)
        }
    }
    const token = localStorage.getItem("token")
    if (token) {
        config.headers.Authorization = 'Bearer ' + token;
    }
    return config
}, error => {
    return Promise.reject(error)
});
//HTTPrequest拦截
axios.interceptors.response.use(res => {
    if (300 == res.data.statusCode) {
        // localStorage.setItem('token','');
        return Vue.prototype.$message.error(res.data.message)
    }
    if (403 == res.data.code) {
        localStorage.removeItem("token")
        return Vue.prototype.$message.error('没有权限，请联系管理员')
    }
    if (401 == res.data.code) {
        localStorage.setItem('token', '');
        return Vue.prototype.$message.error('登录过期，请关闭该页面重新登录！！！')
    }
    return res.data;
}, error => {
    // loadingInstance.close();
    return Promise.reject(new Error(error));
})

export default axios;
